<template>
  <div>
    <el-select  v-model="selectValue" clearable :multiple="isMutiple" :placeholder="placeText" @change="change">

      <!-- 带全选按钮 -->
      <el-checkbox v-if="isSelectAll" v-model="selectCheck"
                   class="m-l-20 select-all"
                   :indeterminate="selectCheckList.length != selectData.length"
                   @change="selectAll">全选</el-checkbox>

      <el-option  v-for="item in selectData"
                  :key="item[keyField]"
                  :value="item[valueField]"
                  :label="item[labelField]"
      >
      </el-option>
    </el-select>
  </div>
</template>

<script>
// 封装select组件
export default {
  props: {
    placeText: {
      type: String,
      default: '全部'
    },
    selectData: {
      type: Array,
      default: ()=>[]
    },
    valueModel: {
      type: String | Number | Array,
      default: ''
    },
    keyField: {
      type: String,
      default: 'id'
    },
    valueField: {
      type: String,
      default: 'id'
    },
    labelField: {
      type: String,
      default: 'label'
    },
    // 是否多选
    isMutiple: {
      type: Boolean,
      default: false
    },
    isSelectAll: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectValue: '',
      selectCheckList: []
    }
  },
  computed: {
    selectCheck: {
      get() {
        if(this.selectCheckList.length == this.selectData.length) {
          return true;
        }
        return false;
      },
      set() {}
    }
  },
  watch: {
    'valueModel':{
      handler(val) {
        this.selectValue = val;
      },
      immediate:true
    },
    'selectValue': {
      handler(val) {
        if(val) {
          this.selectCheckList = val;
        }
      }
    }
  },
  methods: {
    change() {
      this.$emit("update:valueModel", this.selectValue);
    },

    selectAll(checked) {
      this.selectValue = checked ? this.selectData.map(d=>d.id) : [];
      this.change();
    }
  }

}
</script>

<style scoped>
  .select-all {
    margin-left: 5px;
  }
</style>
